package com.code.test.first.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0226.%E7%BF%BB%E8%BD%AC%E4%BA%8C%E5%8F%89%E6%A0%91.md
 * 翻转一棵二叉树。
 */
public class Code226 {

    public static void main(String[] args) {
        TreeNode left10 = new TreeNode(10, null, null);
        TreeNode right20 = new TreeNode(20, null, null);
        TreeNode left30 = new TreeNode(30, null, null);
        TreeNode right40 = new TreeNode(40, null, null);
        TreeNode left3 = new TreeNode(3, left10, right20);
        TreeNode right5 = new TreeNode(5, left30, right40);
        TreeNode root = new TreeNode(1, left3, right5);

        reverseTree(root);
//        System.out.println(ret);
    }

    public static TreeNode reverseTree(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();

        queue.add(root);
        while (!queue.isEmpty()) {

            //这里是每一层的大小，直接圈定好，循环里面再加是为了下一次做准备
            int len = queue.size();
            for (int i = 0; i < len; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) queue.add(node.right);
                TreeNode temp = node.left;
                node.left  = node.right;
                node.right = temp;
            }
        }
        return root;
    }
}
